package com.hanbang.chu_xing_gao_zhao.view_find_classroom;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.entity.FindClassroomStudyData;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic;
import com.hanbang.chu_xing_gao_zhao.utils.BitmapUtil;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 课堂学习资料显示
 *
 * @author yang
 */
public class FindClassroomDataTypeActivity extends BaseDataActivity implements OnClickListener {

    /**
     * 请求参数
     */
    private RequestParams params;

    /**
     * 页大小
     */
    private int pageSize = 10;

    /**
     * 第几页
     */
    private int pageIndex = 1;

    /**
     * 列表数据
     */
    private ArrayList<FindClassroomStudyData> listData = new ArrayList<FindClassroomStudyData>();

    /**
     * 瀑布流控件
     */
    private RecyclerView mRecyclerView;


    /**
     * 瀑布流适配器
     */
    private MyRecyclerViewAdapter adapter;

    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout swipeRefreshLayout;
    /**
     * 旧的集合长度
     */
    private int old = -1;


    /**
     * 排序ID
     */
    private int sort_id = 0;

    /**
     * 类型ID
     */
    private int category_id;
    /**
     * 标题
     */
    private String title;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_classroom_data_type_activity);
        initView();
        setOnClickListener();
        setSwipeRefreshLayout();
    }

    public FindClassroomDataTypeActivity() {
    }


    /**
     * 初始化view
     * pageSize：分页大小，可为空
     * pageIndex：当前页码，为空默认1
     * <p/>
     * category_id：类别，如果获取全部的话，为0
     * sort_id：排序方式，0，销量 1,评价2，价格高3，价格低4，免费5
     */
    private void initView() {
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl_find_classroom_data_type_activity_showList);

        Intent intent = getIntent();
        category_id = intent.getIntExtra("category_id", 1);
        title = intent.getStringExtra("title");

        setTitleMore(View.VISIBLE, View.VISIBLE, title, null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));


        params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "password"));
        params.addBodyParameter("pageSize", pageSize + "");
        params.addBodyParameter("pageIndex", pageIndex + "");
        params.addBodyParameter("category_id", category_id + "");
        params.addBodyParameter("sort_id", sort_id + "");


        if (listData.size() == 0) {

            getHttpList(HttpInterfaces.xuexiziliao_GetList, params);
        }


        mRecyclerView = (RecyclerView) findViewById(R.id.rv_find_classroom_data_type_activity_showList);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        /**
         * 第一个参数，是控件列数或行数，第二参数是控制方向
         */
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));// 设置RecyclerView布局管理器为2列垂直排布
        adapter = new MyRecyclerViewAdapter(listData);
        mRecyclerView.setAdapter(adapter);


    }

    /**
     * 下拉刷新
     */
    private void setSwipeRefreshLayout() {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                listData.clear();
                pageIndex = 1;
                old = -1;

                params = new RequestParams();
                params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "password"));

                params.addBodyParameter("pageSize", pageSize + "");
                params.addBodyParameter("pageIndex", pageIndex + "");
                params.addBodyParameter("category_id", category_id + "");
                params.addBodyParameter("sort_id", sort_id + "");

                getHttpList(HttpInterfaces.xuexiziliao_GetList, params);

            }
        });

    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        //瀑布item 的点击监听
        adapter.setOnClickListener(new OnItemClickListener() {
            @Override
            public void ItemClickListener(View view, int postion) {
                //因为加了一个头部所以位置要-1;
                postion = postion - 1;
                //因为加了一个中部所以位置要再-1;


                Intent intent = new Intent();
                intent.setClass(FindClassroomDataTypeActivity.this.getApplicationContext(), FindClassroomStudyDatailsActivity.class);
                intent.putExtra("id", listData.get(postion).getId());
                intent.putExtra("visitType", 2);
                intent.putExtra("httpUtl", HttpInterfaces.xuexiziliao_Details);
                startActivity(intent);
            }

            @Override
            public void ItemLongClickListener(View view, int postion) {
            }
        });
    }

    /**

     */
    @Override
    public void onClick(View v) {
        Intent intent = new Intent();

        switch (v.getId()) {
            default:

                break;
        }


    }


    /**
     * 获取秘籍列表
     */
    private void getHttpList(String url, RequestParams params) {
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new MyRequestCallBack<String>(FindClassroomDataTypeActivity.this, "加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {
                    JSONObject json = new JSONObject(responseInfo.result);
                    int result = json.getInt("Result");


                    if (result == 0) {
                        JSONArray jsonArray1 = json.getJSONArray("list");
                        // 把数据从接口解析出来
                        listData.addAll(JsonHelper.parseCollection(jsonArray1, ArrayList.class, FindClassroomStudyData.class));
                        adapter.notifyDataSetChanged();

                    } else {

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 适配器
     */
    public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyViewHolderB> implements OnClickListener {
        /**
         * 数据
         */
        private List<FindClassroomStudyData> lists;
        private OnItemClickListener mListener;
        BitmapUtils bitmapUtils;
        /**
         * 上传秘籍
         */
        private LinearLayout uploading;
        /**
         * 加载
         */
        private TextView loading;

        // view的type：头部，内容，中部标题
        private static final int TYPE_HEADER = 1, TYPE_ITEM = 2, LOADING = 3;
        /**
         * 申请开课
         */
        private LinearLayout apply;
        /**
         * 最热
         */
        private LinearLayout hottest;
        /**
         * 厨师-管理
         */
        private LinearLayout cookingManager;
        /**
         * 厨房-管理
         */
        private LinearLayout kitchenManager;
        /**
         * 前厅-管理
         */
        private LinearLayout vestibuleManager;
        /**
         * 销售-管理
         */
        private LinearLayout saleManager;
        /**
         * 财务-管理
         */
        private LinearLayout financeManager;
        /**
         * 人员-培训
         */
        private LinearLayout personManager;


        public MyRecyclerViewAdapter(List<FindClassroomStudyData> lists) {

            bitmapUtils = BitmapUtil.getBitmapUtils(FindClassroomDataTypeActivity.this, MyApplication.bitmapCachePath);

            if (lists != null) {
                this.lists = lists;
            } else {
                this.lists = new ArrayList<FindClassroomStudyData>();
            }

        }


        @Override
        public void onClick(View v) {
            MorePopupWindowPublic popup;
            Intent intent = new Intent();
            switch (v.getId()) {
                // 排序的调用
                case R.id.ll_findclassroom_top_title_data_hottest:
                    popup = new MorePopupWindowPublic(getApplicationContext(), R.layout.item_popupwindow_public, sortId, 8);
                    popup.showPopupWindow(hottest.getChildAt(0), 3);

                    // 排序
                    if (popup != null) {
                        popup.setOnClickCallback(new MorePopupWindowPublic.OnClickCallback() {

                            @Override
                            public void onClick(MorePopupWindowPublic morePopWindow, Object number, String content) {

                                for (int i = 0; i < morePopWindow.parentView.size(); i++) {
                                    if ((Integer) number == i) {
                                        sort_id = (int) number;
                                        listData.clear();
                                        pageIndex = 1;
                                        old = -1;
                                        ((TextView) hottest.getChildAt(0)).setText(content);
                                        RequestParams paramsA = new RequestParams();
                                        paramsA.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                                        paramsA.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "password"));
                                        paramsA.addBodyParameter("pageSize", pageSize + "");
                                        paramsA.addBodyParameter("pageIndex", pageIndex + "");
                                        paramsA.addBodyParameter("category_id", category_id + "");
                                        paramsA.addBodyParameter("sort_id", sort_id + "");

                                        MyLog.e("text", "sort_id*****" + sort_id);//*********************

                                        getHttpList(HttpInterfaces.xuexiziliao_GetList, paramsA);

                                    }
                                }
                            }
                        });
                    }
                    break;


                default:
                    break;

            }


        }

        public void setOnClickListener(OnItemClickListener listener) {
            this.mListener = listener;

        }

        @Override
        public MyViewHolderB onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = null;
            // 根据类型填充不同布局
            switch (viewType) {
                //添加头部
                case TYPE_HEADER:
                    view = LayoutInflater.from(FindClassroomDataTypeActivity.this).inflate(R.layout.find_classroom_top_title_data, parent, false);
                    ((LinearLayout) view.findViewById(R.id.ll_findclassroom_top_title_data_praent)).setVisibility(View.GONE);
                    ((LinearLayout) view.findViewById(R.id.ll_find_classroom_data_uploading)).setVisibility(View.GONE);
                    ((ImageView) view.findViewById(R.id.lv_findclassroom_top_title_data_titlePicture)).setVisibility(View.GONE);
                    hottest = (LinearLayout) view.findViewById(R.id.ll_findclassroom_top_title_data_hottest);
                    hottest.setOnClickListener(this);


                    break;
                //内容
                case TYPE_ITEM:
                    view = LayoutInflater.from(FindClassroomDataTypeActivity.this).inflate(R.layout.find_classroom_data, parent, false);
                    break;

                //加载更多
                case LOADING:

                    view = LayoutInflater.from(FindClassroomDataTypeActivity.this).inflate(R.layout.list_foot_loading, parent, false);
                    loading = (TextView) view.findViewById(R.id.tv_list_foot_loading);
                    loading.setOnClickListener(this);
            }

            //更改字体
            UiUtils.applyFont(view);
            MyViewHolderB viewHolder = new MyViewHolderB(view);
            return viewHolder;
        }


        @Override
        public void onBindViewHolder(final MyViewHolderB holder, int position) {
            switch (holder.getItemViewType()) {
                //使用头单独占一行
                case TYPE_HEADER:
                    // 最最关键一步，设置当前view占满列数，这样就可以占据两列实现头部了
                    StaggeredGridLayoutManager.LayoutParams clp = (StaggeredGridLayoutManager.LayoutParams) holder.head.getLayoutParams();
                    /**
                     * 如果设置为true，该项目将布局采用全量程范围。这意味着，如果方向
                      *是垂直的，认为将有充分的宽度;如果方向是水平的，视图将
                      *有充分的高度。
                       *参数fullSpan如果此项目应遍历所有的跨度。
                     */
                    clp.setFullSpan(true);

                    break;
                //内容的展示
                case TYPE_ITEM:
                    if (lists.size() == 0 || lists.size() < position) {
                        return;
                    }
                    //因为传过来的position是从0开始，所以要减1.
                    position = position - 1;
                    ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();// 得到item的LayoutParams布局参数
                    holder.itemView.setLayoutParams(params);// 把params设置给item布局

                    bitmapUtils.configDefaultLoadFailedImage(R.drawable.default_white);
                    bitmapUtils.display(holder.picture, SystemTools.getHttpFileUrl(lists.get(position).getImg_url()));

                    holder.name.setText(lists.get(position).getTitle());
                    holder.price.setText("¥：" + String.valueOf(lists.get(position).getPrice()));
                    holder.descaribe.setText(lists.get(position).getRemark());
                    holder.sales.setText(String.valueOf(lists.get(position).getSharecount()));
                    holder.grade.setText(String.valueOf(lists.get(position).getPingfen()));


                    //设置item 的监听
                    if (mListener != null) {// 如果设置了监听那么它就不为空，然后回调相应的方法
                        /**
                         * 点击监听
                         */
                        holder.itemView.setOnClickListener(new OnClickListener() {

                            public void onClick(View v) {
                                int pos = holder.getPosition();// 得到当前点击item的位置pos
                                mListener.ItemClickListener(holder.itemView, pos);// 把事件交给我们实现的接口那里处理
                            }
                        });

                        /**
                         * 长按监听
                         */
                        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                int pos = holder.getPosition();// 得到当前点击item的位置pos
                                mListener.ItemLongClickListener(holder.itemView, pos);// 把事件交给我们实现的接口那里处理
                                return true;
                            }
                        });
                    }


                    break;


                //使用尾部独占一行
                case LOADING:

                    //如果没有新的数据则隐藏加载按键
                    if (lists.size() == old) {
                        holder.bottom.setVisibility(View.GONE);
                        return;
                    } else {
                        holder.bottom.setVisibility(View.VISIBLE);
                    }

                    //加载尾部布局
                    StaggeredGridLayoutManager.LayoutParams clp1 = (StaggeredGridLayoutManager.LayoutParams) holder.bottom.getLayoutParams();

                    clp1.setFullSpan(true);


                    //自动加载
                    if (position - 1 == listData.size()) {

                        if (old == lists.size()) {
                            return;
                        }
                        ++pageIndex;
                        RequestParams paramsA = new RequestParams();
                        paramsA.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                        paramsA.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                                FindClassroomDataTypeActivity.this, MySharedPreferences.USER_DATA, "password"));
                        paramsA.addBodyParameter("pageSize", pageSize + "");
                        paramsA.addBodyParameter("pageIndex", pageIndex + "");
                        paramsA.addBodyParameter("category_id", category_id + "");
                        paramsA.addBodyParameter("sort_id", sort_id + "");
                        getHttpList(HttpInterfaces.xuexiziliao_GetList, paramsA);

                        old = lists.size();

                    }


                    break;

            }
        }

        @Override
        public int getItemCount() {
            return lists.size() + 2;
        }

        @Override
        public int getItemViewType(int position) {
            //添加一个底部加载使用
            if (position == lists.size() + 1 && lists.size() > 1) {
                return LOADING;
            }

            // 位置为0的话类型为头部，其余为内容
            return position = position == 0 ? TYPE_HEADER : TYPE_ITEM;
        }
    }


    /**
     * 内容控件的初始化
     */
    class MyViewHolderB extends RecyclerView.ViewHolder implements OnClickListener {
        public ImageView picture;


        public TextView price;
        public TextView name;
        public TextView descaribe;
        public TextView sales;
        public TextView grade;

        public LinearLayout head;
        public LinearLayout bottom;


        public MyViewHolderB(View itemView) {
            super(itemView);
            //头部
            if (itemView.getId() == R.id.find_classroom_top_title_data) {
                head = (LinearLayout) itemView.findViewById(R.id.find_classroom_top_title_data);
                //内容
            } else if (itemView.getId() == R.id.ll_list_foot_loading_parent) {

                bottom = (LinearLayout) itemView.findViewById(R.id.ll_list_foot_loading_parent);
                bottom.setOnClickListener(this);
                //内容
            } else {
                picture = (ImageView) itemView.findViewById(R.id.iv_find_classroom_data_picture);
                name = (TextView) itemView.findViewById(R.id.tv_find_classroom_data_name);
                price = (TextView) itemView.findViewById(R.id.tv_find_classroom_data_price);
                descaribe = (TextView) itemView.findViewById(R.id.tv_find_classroom_data_descaribe);

                sales = (TextView) itemView.findViewById(R.id.tv_find_classroom_data_sales);
                grade = (TextView) itemView.findViewById(R.id.tv_find_classroom_data_grade);
            }
        }

        @Override
        public void onClick(View v) {

        }
    }


    /**
     * 定义回调接口
     */
    interface OnItemClickListener {
        void ItemClickListener(View view, int postion);

        void ItemLongClickListener(View view, int postion);
    }


}


